if (typeof(QS_PROTOCOL) == "undefined") {
    QS_PROTOCOL = "http://";
}
if(typeof(STATIC_VAR)=="undefined"){
    STATIC_VAR={marketIndexSessionExists:false,marketsFirstLoad:false};
}
function SiteBuilder_firstLoadLoginPage(){
    if (STATIC_VAR.marketsFirstLoad == false) {
        $(document.body).append("<iframe style='display:none' onreadystatechange='STATIC_VAR.marketIndexSessionExists=true' onload='STATIC_VAR.marketIndexSessionExists=true' src='" + QS_PROTOCOL + "awrd.morningstar.com/advisor/login/instlgn.asp?instid=SBDEMO&login=Support_1&pwd=Support_1'></iframe>");
        STATIC_VAR.marketsFirstLoad = true;
    }
}
var QS_Market = function(){
    this.containerId = null;
    this.container = null;
    this.id = null;
    this.profile = null;
    this.tabMenu = null;
    this.iframeWrap = null;
	this.iframeHeight;//added by wind, to make the iframe height same with the body
    this.refreshEl = null;
    this.i = 0;
    this.interval = null;
};
QS_Market.prototype = {
    init: function(ContainerId, Profile, Sid){
        this.containerId = ContainerId;
        this.container = $('#' + ContainerId);
        this.id = Sid;
        this.profile = Profile;
        var self = this;
        SiteBuilder_firstLoadLoginPage();
        if (STATIC_VAR.marketIndexSessionExists == false) {
            this.interval = setInterval(function(){
                if (self.i < 10) {
                    self.i++;
                    self.loadIframe(self);
                } else {
                    clearInterval(self.interval);
                }
            }, 1000);
            return;
        }
        this.loadIframe(this);
    },
    loadIframe: function(self){
        if (STATIC_VAR.marketIndexSessionExists == false) {
            return;
        }
        var ifm = self.profile.iframes;
        var tdata = [];
        self.showLoading(true);
        if(self.profile.refresh){
            self.refreshEl = $("<div class='markets-refresh "+(typeof(self.profile.rfStyle)=="undefined"?'':self.profile.rfStyle)+"'><a href='javascript:void(0)'>Refresh</a></div>");
            self.container.append(self.refreshEl);
            self.refreshEl.bind("click", function(){
                self.refreshIframe();
            });
        }
        self.iframeWrap = $("<div class='iframe-wrap'></div>");
        self.container.append(self.iframeWrap);
        for (var i = 0; i < ifm.length; i++) {
            if($.browser.safari&&ifm[i].title=="Sector Delta"){
                continue;
            }
            tdata.push({
                txt: ifm[i].title,
                id: i
            });
        }
        
        if (self.profile.align == "tab") {
            self.tabMenu = new Util.TabMenu(self.iframeWrap[0], tdata, null, {needTitle:true});
        }
        
        var margintop = 0;//edited by wind 20120104
        var iii = 0;
		this.iframeHeight=$('body').height()-38;	
        for (var i = 0; i < ifm.length; i++) {
            if($.browser.safari&&ifm[i].title=="Sector Delta"){
                continue;
            }
            //margintop = typeof(ifm[i].margintop) == "undefined" ? 10 : ifm[i].margintop;//edited by wind 20120104			
            if (self.profile.align == "tab") {
                self.tabMenu.tabs[iii++].panel.append("<iframe frameborder='none' class='market-iframe' style='width:100%;height:"+this.iframeHeight+"px;border:0;margin-top:" + margintop + "px;margin-left:0px;' src='" + ifm[i].url + "'></iframe>");
            } else if (self.profile.align == "none") {
                self.iframeWrap.append("<iframe frameborder='none' class='market-iframe' style='width:100%;height:"+this.iframeHeight+"px;border:0;margin-top:" + margintop + "px;margin-left:"+(typeof(ifm[i].marginleft)=="undefined"?0:ifm[i].marginleft)+"px;' src='" + ifm[i].url + "'></iframe>");
            } else if (self.profile.align == "line") {
                self.iframeWrap.append("<iframe frameborder='none' class='market-iframe' style='width:100%;height:"+this.iframeHeight+"px;border:0;margin-top:" + margintop + "px;margin-left:" + (i == 0 ? 0 : -473) + "px;float:left' src='" + ifm[i].url + "'></iframe>");
            }
        }
        if (self.profile.align == "line") {
            self.iframeWrap.css({
                "width": ifm.length * 600 + "px"
            });
        }
        
        if (self.interval != null) {
            clearInterval(self.interval);
        }
        
        setTimeout(function(){self.hideLoading();},8000);
    },
    refreshIframe:function(){       
        var self=this;
        self.showLoading(true);     
        var ifms = this.container.find(".market-iframe");
        for (var i = 0; i < ifms.length; i++) {
            ifms[i].src = ifms[i].src;
        }
        setTimeout(function(){self.hideLoading();},3000);
    },
    fileMenuCallback:function(v){
        if(v=="refresh"){
            this.refreshIframe();
        }
    },
    changeOutSize: function(w, h){
        var parent = this.container.parent();
        w = w || parent.width();
        h = h || parent.height() + 1;
    },
    _onLoginIframeReady: function(){
        STATIC_VAR.marketIndexSessionExists = true;
    },
    updateData:function(){}
};
/**
//subtype 14_1
var QS_MarketIdx = function(){
    this.containerId = null;
    this.container = null;
    this.id = null;
    this.profile = {
		chartCfg:{}
	};
	
    this.tabMenu = null;
	this.dataGrid = null;
	this.activeRow = null;
	this.miniChartDom = null;
	this.miniChartHeight = 0;
	this.miniChart = null;
	this.lastSubscribeTicker = null;
	this.menuContex = [{id: 1,txt: 'U.S.',closable: false},{id: 2,txt: 'Asian',closable: false},{id: 3,txt: 'European',closable: false}];
	this.gridData = {
		1:['0P00001FJG','0P00001G7J', '0P00001G7B', '0P00001GJH', '0P00001GJK'],//US
        2:['0P00001GJH','0P00001GJI', '0P00001GJJ', '0P00001GJK'],              //Morningstar
        3:['0P00006NNM', '0P00006MR4', '0P00001FL8', '0P00001G5J', '0P00001MUH'],//Asian
        4:['0P00001IS1','0P00008ICX','0P00006G3M', '0P00006F1A', '0P00006NOT']//European
	}
	this.gKeyList = {
		1:[],
		2:[],
		3:[]
	};
	this.chart = null;
	this.HTML = '<div class="qs-market">'+
					'<div class="tabmenu"></div>'+
					'<div class="grid"></div>'+
					'<div class="minichart" style="display:none;"></div>'+
				'</div>';
	
	this.tValidation = new tickerValidation(17);
	this.chartScopeDdl = null;
};
QS_MarketIdx.prototype = {
	init: function(ContainerId, Profile, Sid){
		var self =this;
		this.containerId = ContainerId;
		this.container = $('#' + ContainerId);
		this.id = Sid;
		this.profile = Profile;
		this.el = $(this.HTML);
		this.el.appendTo(this.container);
		this.initMenu();
		this.createSettingPannel();
	},
	initMenu: function(){
		var self = this;
		var cb = {
			onActive: function(tab){
				self.currentTabMenuId = tab.id;
				self.activeRow = null;
				if (!self.dataGrid) {
					self.initGrid();
				}else{
					self.el.find(".minichart").appendTo(self.el);
				}
				self.reBuildGridData(tab.id);
			}
		};
		this.tabMenu = new Util.TabMenu(this.el.find(".tabmenu"), this.menuContex, cb, {
			tabsList: false,
			vertical: false
		});
	},
	initGrid: function(){
		var self = this;
		var column = [{
			header: 'id',
			dataIndex: 'id',
			dataType: 'string',
			hide: true,
			width: "0"
		}, {
			header: 'Symbol',
			dataIndex: 'Symbol',
			dataType: 'string',
			width: "30%"
		}, {
			header: 'Last',
			dataIndex: 'LastPrice',
			align: 'right',
			dataType: 'float',
			width: "25%"
		}, {
			header: 'Chg',
			dataIndex: 'Chg',
			align: 'right',
			dataType: 'float',
			className: 'bold-cell',
			width: "22%"
		}, {
			header: 'Chg%',
			dataIndex: 'Chg%',
			align: 'right',
			dataType: 'float',
			className: 'bold-cell',
			width: "23%"
		}];
		
		var self=this;
		var cb = {
			onRowSelected: function(e, row){
				var gkey = row.id;//self.gKeyList[self.currentTabMenuId]["gKeyList"][0];
				if (self.activeRow !== row) {
					if (typeof(self.activeRow) != "undefined" && self.activeRow != null) { // wrap the old row.
						self.activeRow.el.animate({
							height: '20px'
						}, {
							duration: "normal"
						});
					}
					row.el.animate({
						height: (self.miniChartHeight) + 'px'
					}, {
						duration: "normal"
					});
					self.activeRow = row;
					self.drawMiniChart(row, gkey);
				}
			}
		};
		this.dataGrid = new Util.DataGrid(this.el.find(".grid"), [], {
			column: column,
			width: "100%",
			autoWidth: true,
			height: 80,
			autoHeight: true,
			headerRow: false,
			htmlLayer: 'div',
			rowDragable: true,
			rowDropable: true,
			rowDragDropGroup: 'GRID1'
		}, cb);
	},
	createSettingPannel: function(){
		var  self = this;
		var settingPN = this.__winObj.settingPanelObj.settingPN;
		var settingPNGroupBox = new Util.GroupBox(settingPN.find(".wrap"), [{
			name: 'Display',
			id: 1
		}], {
			width: 150,
			groupBoxHeight: 150
		});		
		settingPNGroupBox.getGroup(1).bd.html('<h5 style="text-indent:3px;"> Chart Scope</h5>');
		
		this.chartScopeDdl = new Util.DropDownList(settingPNGroupBox.getGroup(1).bd, function(t, v){
			self.profile.chartRange = v;
			self.changChartRange(v);
		}, [{
			txt: '1 Day',
			val: '1d'
		}, {
            txt: '5 Days',
            val: '5d'
        }, {
			txt: '1 Month',
            val: '1m'
		}, {
            txt: '3 Months',
            val: '3m'
        }, {
            txt: '6 Months',
            val: '6m'
        }, {
            txt: '1 Year',
            val: '1y'
        }, {
            txt: '2 Years',
            val: '2y'
        }], {
			width: 146
		});
	},
	changChartRange:function(r){
		var l = r.length - 1, step = parseInt(r.substr(0,l));
		var today = new Date(), todayIdx = RTQ_ChartUtil.toDateIndex(today);
		var cfg = {"endIndex":todayIdx}; 
		switch (r.charAt(l)) {
			case "d":
				cfg["freq"] = 1;
				cfg["startIndex"] = todayIdx - (step - 1);
				cfg["days"] = step;
				break;
			case "m":
				var y = today.getFullYear(), m = today.getMonth();
				if (m > step - 1) {
					m = m - step;
				}
				else {
					y -= 1;
					m = m + 12 - step;
				}
				var startDate = new Date(y, m, today.getDate());
				cfg["startIndex"] = RTQ_ChartUtil.toDateIndex(startDate);
				
				if (todayIdx - cfg["startIndex"] >= 60) {
					cfg["freq"] = "d";
				}else{
					cfg["freq"] = 30;
				}
				break;
			case "y":
			    cfg["freq"] = "d";
				var y = today.getFullYear() - step, m = today.getMonth(),d = today.getDate();
				var startDate = new Date(y, m, d);
                cfg["startIndex"] = RTQ_ChartUtil.toDateIndex(startDate);
				break;
			default:
				break;
		}
		
		
		this.profile.chartCfg = cfg||{};
		if(this.miniChart&&this.activeRow){
			var gkey = this.activeRow.id;
			this.drawMiniChart(this.activeRow, gkey);
		}
	},
    drawMiniChart:function(row, gkey){
		if(!this.miniChart){
			this.initMiniChart(gkey);
			this.el.find(".minichart").css("display","block");
		}else{
			this.miniChart.unSubscribe(this.lastSubscribeTicker,this.lastSubscribeTicker);
			this.subscribeTicker(gkey);
		}
		row.el.append(this.el.find(".minichart"));
	},
	_isNull: function(d, fixPoint, needColor){
		if (typeof(d) == 'undefined' || !d) {
			return "";
		}
		else 
			if (needColor) {
				return fixPoint ? d.toFixed(fixPoint) : d;
			}
			else {
				var c = (d >= 0 ? QS_Style.greenFontColor : QS_Style.redFontColor);
				return fixPoint ? "<div style='color:"+c+"'>"+d.toFixed(fixPoint)+"</div>" : "<div style='color"+c+"'>"+d+"</div>";
			}
	},
	_fillDList: function(gKeyList){
		var data = [];
		for (var i = 0; i < gKeyList.length; i++) {
			var d = {};
			d["id"] = gKeyList[i];
			d["Symbol"] = this._isNull(gData[gKeyList[i]]["ticker"]);
			d["LastPrice"] = this._isNull(gData[gKeyList[i]]["LastPrice"],2);
			d["Chg"] = this._isNull(gData[gKeyList[i]]["Chg"],2);
			d["Chg%"] = this._isNull(gData[gKeyList[i]]["Chg%"],2);
			data.push(d);
		}
		return data;
	},
	initMiniChart:function(gkey,el){
		this.miniChart = new minichart(this.el.find(".minichart"), {width:this.profile["width"], height:this.miniChartHeight-20,lineType:"montain",showX:true,showY:true});
		this.subscribeTicker(gkey);
	},
	subscribeTicker: function(gkey){
		var self = this;
		var pid = gData[gkey]["secId"] || gData[gkey]["performanceId"];
		this.showLoading();
		this.tValidation.checkTickers(pid, function(o){
			self.lastSubscribeTicker = o[0];
			self.miniChart.subscribe(o[0], o[0],self.profile.chartCfg,function(){
				self.hideLoading();
			});
		});
	},
	calMinChartSize:function(){  // cal miniChart Size.
        var l = this.gKeyList[this.currentTabMenuId]["gKeyList"].length;
        this.miniChartHeight = this.profile["height"]-20*l - 23; 
	},
	reBuildGridData: function(id){
		if (typeof(this.gKeyList[id]["gKeyList"]) == 'undefined' || this.gKeyList[id]["gKeyList"].length == 0) {
			var ls = this.gridData[id];
			this.showLoading();
			var self = this;
			this.tValidation.checkTickers(ls, function(gKeyList){
				self.hideLoading();
				self.gKeyList[id]["gKeyList"] = gKeyList;
				var gKeyMap = {};
				for (var i = 0; i < gKeyList.length; i++) {
					gKeyMap[gKeyList[i]] = i;
				}
				self.gKeyList[id]["gKeyMap"] = gKeyMap;
				self.dataGrid.reBindData(self._fillDList(gKeyList));
				self.calMinChartSize();
				for (var i = 0; i < gKeyList.length; i++) {
					self.forceUpdateData(gKeyList[i], id);
				}
			});
		}
		else {
			var gKeyList = this.gKeyList[id]["gKeyList"];
			this.dataGrid.reBindData(this._fillDList(gKeyList));
			this.calMinChartSize();
			for (var i = 0; i < gKeyList.length; i++) {
				this.forceUpdateData(gKeyList[i], id);
			}
		}
	},
	forceUpdateData: function(gKey, id){
		var aData = {};
		var cols = this.dataGrid.getColumnCfg(), field;
		for (var c in cols) {
			field = cols[c].dataIndex;
			if (field == "Up/Down") 
				field = "Chg";
			aData[field] = {
				dataType: cols[c].dataType,
				value: gData[gKey] == null ? null : push.proxy.getMarketQuoteData(gKey, field).value
			};
		}
		this.updateData(gKey, aData, false, id);
	},
	updateData: function(gKey, aData, needFlash, currentId){
		if (this.gKeyList[this.currentTabMenuId]["gKeyMap"]&&this.gKeyList[this.currentTabMenuId]["gKeyMap"].hasOwnProperty(gKey)) {
			var _flashMethod = needFlash === false ? (function(){
			}) : flash;
			for (var field in aData) {
				var type = aData[field].dataType;
				var gValue = aData[field].value;
				var oldData = aData[field].oValue;
				
				var data = gValue;
				var el = this.dataGrid.DOMMap[gKey][field];
				switch (field) {
					case 'LastPrice':
						_flashMethod(el, data, oldData);
						var securitytype = gData[gKey]["type"];
						data = formatDoubledata(data, securitytype);
						break;
					case 'Chg':
					case 'Chg%':
						if (needFlash !== false) {
							flashWithDirectional(el, data, oldData, data >= 0);
						}
						else {
							el.style.color = data >= 0 ? QS_Style.greenFontColor : QS_Style.redFontColor;
						}
						var securitytype = gData[gKey]["type"];
						data = formatDoubledata(data, securitytype);
						break;
					default:
						break;
				}
				if(field == 'Chg%'&&/^[-\+]?\d+(\.\d+)?$/.exec(data)){
                    data = data + "%";
                }
				if (el && field != 'Symbol') {
					el['innerHTML'] = data;
				}				
			}
		}
	},
	fileMenuCallback: function(v){
		if (v == "refresh") {
			//this.refreshIframe();
		}
	},
	changeOutSize: function(w, h){
		var parent = this.container.parent();
		w = w || parent.width();
		h = h || parent.height() + 1;
		$.extend(true, this.profile, {width:w,height:h});
		
		this.el.height(h);
		this.el.find(".grid").height(h - 23);
		this.calMinChartSize();
		if (this.activeRow !== undefined && this.activeRow) {
			this.miniChart.changeOutSize(w,this.miniChartHeight-20);
			this.activeRow.el.animate({
				height: this.miniChartHeight+'px'
			}, {
				duration: "fast"
			});
		}
	}
};


//subtype 14_2
var QS_MarketBarometer = function(){
    this.HTML = '<div class="qs_marketbarometer">' +
	    '<div class="style-main" style="height:50%;">' +
	        '<div class="main">' +
	          '<div class="1d box"></div>' +
	          '<div class="clorbox"></div>' +
	        '</div>' +
	        '<div class="center-gap"></div>' +
	        '<div class="sub">' +
	            '<div class="1w box"></div>' +
	            '<div class="1m box"></div>' +
	            '<div class="3m box"></div>' +
	            '<div class="1y box"></div>' +
	            '<div class="3y box"></div>' +
	        '</div>' +
		'</div>' +
		'<div class="grid-list" style="height:50%;">' +
		'</div>' +
    '</div>';
    
    this.dayRanges = ['1d', '1w', '1m', '3m', '1y', '3y'];
    this.colorbox = null;
    this.mainBox = null;
    this.msStyleBoxs = [];
	this.profile = {};
}

QS_MarketBarometer.prototype = {
    init: function(ContainerId, Profile, Sid){
        this.containerId = ContainerId;
        this.container = $('#' + ContainerId);
        this.id = Sid;
        $.extend(this.profile, Profile);
        this.el = $(this.HTML);
        this.el.appendTo(this.container);
		this.colorbox = new QS_MSStyleBoxcolorGroup(this.el.find('.clorbox'));
        this.initMSStyleBoxs();
		this.initDTGrid();
        this.changeOutSize();
		
		QS_MSStyleBoxDataManager.register(this);
    },
	initDTGrid: function(){
		this.dtgrid = new Util.DataGrid(this.el.find('.grid-list'), {}, {
			column: [{
				header: "rowid",
				dataIndex: 'rowid',
				width: 0,
				dataType: 'string',
				hide: true
			}, {
				header: "Morningstar Indexes",
				dataIndex: 'symbols',
				width: '50%',
				dataType: 'string'
			}, {
				header: "Return %",
				dataIndex: 'return',
				width: '50%',
				align: 'right',
				dataType: 'html'
			}],
			autoWidth: true,
			height: 90,
			htmlLayer: 'div',
			//headerRow: false,
			rowDragable: true,
			rowDropable: true,
			rowDragDropGroup: 'GRID1'
		}, {});
		
		var symbols = ['Lagge Value', 'Large Core', 'Large Growth', 'Mid Value', 'Mid Core', 'Mid Growth', 'Small Value', 'Small Core', 'Small Growth'];
		var data = [];
		for (var i = 0, l = symbols.length; i < l; i++) {
			data.push({'rowid': i, 'symbols': symbols[i], 'return': ''});
		}
		this.dtgrid.reBindData(data);
	},
    initMSStyleBoxs: function(){
        this.mainBox = new QS_MSStyleBox(this.el.find(".style-main .main ." + this.dayRanges[0]), {
            dayRangesd: this.dayRanges[0],
			scope:15,
			showRtn: true,
			showRange: false,
			showHeader:true,
			isMainRange:true
        }, this.colorbox);
        //var subContainers = this.el.find(".sub div");
        
        for (var idx = 1; idx < this.dayRanges.length; idx++) {
            var subbox = new QS_MSStyleBox(this.el.find(".style-main .sub ." + this.dayRanges[idx]), {
                dayRange: this.dayRanges[idx],
				scope:idx*10,
				showRange: true
            }, this.colorbox);
            this.msStyleBoxs.push(subbox);
        }
    },
    updateData: function(){},
	flush:function(){
		
	},
    changeOutSize: function(w, h){
        var parent = this.el.parent().parent();
        w = w || parent.width();
        h = h || parent.height() + 1;
        this.width = w;
        this.height = h;
        this.el.css({
            width: w,
            height: h
        });
        
        this.mainBox.reSize();
        $.each(this.msStyleBoxs, function(){
            this.reSize();
        });
    }
};

//subtype 14_5
var QS_MarketSectors = function(){
	this.id = null;
	this.container = null;
	this.profile = null;
	
	//this.dataManager = null;
	this.tabmenu = null; 
	this.delta = null;
	this.valuation = null;
};
QS_MarketSectors.prototype = {
	init: function(containerId, profile, sId){
		this.container = $('#' + containerId);
		this.id = sId;
		this.profile = profile;
		
		this.initTabMenu();
		if (!QS_MarketSectors.dataManager) {
			this.initDataManager();
		}else{
			this.dataManager = QS_MarketSectors.dataManager;
			this.fillData();
		}
		
        this.changeOutSize();
	},
	fillData: function(){
		this.delta.initColor();
		this.delta.show('sdmkt', '1d');
	},
	initDataManager:function(){
		QS_MarketSectors.dataManager = {
			dataReadyStatus: false,
			gKeyList: ['U.S. Market', 'Cyclical', 'Basic Materials', 'Consumer Cyclical', 'Fianacial Services', 'Real Estate', 'Defensive', 'Consumer Defensive', 'Healthcare', 'Utilities', 'Sensitive', 'Communication Services', 'Energy', 'Industrials', "Technology"],
			SID: ['XIUSA0010V', 'F00000LJGU', 'F00000LJ8U', 'F00000LJ8Y', 'F00000LJ96', 'F00000LJ9C', 'F00000LJGW', 'F00000LJ90', 'F00000LJ98', 'F00000LJ9G', 'F00000LJGY', 'F00000LJ8W', 'F00000LJ92', 'F00000LJ9A', 'F00000LJ9E'],
			PID: ['0P00001GJX', '0P0000RTEW', '0P0000RT4M', '0P0000RT4R', '0P0000RT4Z', '0P0000RT55', '0P0000RTEY', '0P0000RT4T', '0P0000RT51', '0P0000RT59', '0P0000RTF0', '0P0000RT4P', '0P0000RT4V', '0P0000RT53', '0P0000RT57'],
			type: {
				'sdservice': ['0P0000RTF0', '0P0000RT4P', '0P0000RT4V', '0P0000RT53', '0P0000RT57'],//Sensitive
				'sdinfo': ['0P0000RTEW', '0P0000RT4M', '0P0000RT4R', '0P0000RT4Z', '0P0000RT55'],//Cyclical
				'sdmfg': ['0P0000RTEY', '0P0000RT4T', '0P0000RT51', '0P0000RT59'],//Defensive
				'sdmkt': ['0P00001GJX', '0P0000RTF0', '0P0000RTEW', '0P0000RTEY']//US Market
			},
			frequencyDataPoint: {'1d': 'pd003', '1w': 'pd005', '1m': 'pd007', '3m': 'pd009', '1y': 'pd00d', '3y': 'pd00f'}
		}
		
		$.extend(QS_MarketSectors.dataManager, {
			init:function(){
				for (var idx = 0, l = Math.min(this.PID.length, this.SID.length); idx < l; idx++) {
					var gKey = "9999:" + this.gKeyList[idx];
					gIdMap[this.PID[idx]] = gKey;
					gIdMap[this.SID[idx]] = gKey;
					gData[gKey] = {};
					gData[gKey]["checked"] = true;
					gData[gKey]["performanceId"] = this.PID[idx];
					gData[gKey]["secId"] = this.SID[idx];
				}
				
				this.subscribeTicker();
			},
			subscribeTicker: function(){
				var self = this;
				getStaticData(this.PID, function(o){
					self.dataReadyStatus = true;
				});
			},
			getGridData: function(t, f){
				var dpoint = this.frequencyDataPoint[f];
				var data = [], tList = this.type[t];
				for (var idx = 0, l = tList.length; idx < l; idx++) {
					var d = {}, gKey = gIdMap[tList[idx]];
					d['rowid'] = idx + 1;
					d['Symbols'] = gKey.substr(5);
					d['chg'] = parseFloat(gData[gKey][dpoint], 10).toFixed(2);
					data.push(d);
				}
				return data;
			},
			getChg:function(f){
				var dpoint = this.frequencyDataPoint[f];
                var data = [], dlist = this.type['sdmkt'];
                for (var idx = 0, l = dlist.length; idx < l; idx++) {
                    var gKey = gIdMap[dlist[idx]];
                    data[idx] = parseFloat(gData[gKey][dpoint],10).toFixed(2);
                }
                return data;
			}
		});
		QS_MarketSectors.dataManager.init();
		this.dataManager = QS_MarketSectors.dataManager;
		
		var  self = this;
		function delayInvoke(delayTime){
			window.setTimeout(function(){
				if (self.dataManager.dataReadyStatus === true) {
					self.fillData();
				}
				else {
					delayInvoke(delayTime)
				}
			}, delayTime);
		}
		delayInvoke(100);
	},
	initTabMenu:function(){
		var self = this;
		this.tabmenu = new Util.TabMenu(this.container, [{
            txt: "Sector Delta",
            val: "delta",
            closable:false
        }, {
            txt: "Sector Valuation",
            val: "valuation",
            closable:false
        }], {
            onActive: function(tab){
                if (tab.val == 'delta' && !self.delta) {
                    self.initDelta(tab.panel);
                }
                else 
                    if (tab.val == 'valuation' && !self.valuation) {
                        self.initValuation(tab.panel);
                    }
            }
        }, {
            tabsList: false,
            closeAction: 'hide',
            autoSlideToActiveTab: false,
            activeTabId:"delta",
            rearrange: false
        });
	},
	initDelta: function(panel){
		var sector = this;
		this.delta = {
			dom: null,
			dtgrid: null,
			type: ['sdservice', 'sdinfo', 'sdmfg', 'sdmkt'],
			frequencyRange: {'1d':'Day Change %', '1w':'1-Week Change %', '1m':'1-Month Change %', '3m':'3-Month Change %', '1y':'1-Year Change %', '3y':'3-Year Change %'}
		};
		$.extend(this.delta,{
			init:function(){
				var html = '<div class="qs-triangle-container">' +
		            '<div class="main clearfix">' +
		                '<div class="1d box"><div class="qs-ui-triangle"><div class="sdservice l5"></div><div class="sdinfo l3"></div><div class="sdmfg l1"></div><div class="sdmkt l2"></div></div></div>' +
		            '</div>' +
		            '<div class="sub clearfix">' +
		                '<div class="1w box"><div class="qs-ui-triangle-sm"><div class="sdservice l5"></div><div class="sdinfo l3"></div><div class="sdmfg l1"></div><div class="sdmkt l2"></div></div></div>' +
		                '<div class="1m box"><div class="qs-ui-triangle-sm"><div class="sdservice l1"></div><div class="sdinfo l2"></div><div class="sdmfg l3"></div><div class="sdmkt l4"></div></div></div>' +
		                '<div class="3m box"><div class="qs-ui-triangle-sm"><div class="sdservice l1"></div><div class="sdinfo l7"></div><div class="sdmfg l5"></div><div class="sdmkt l4"></div></div></div>' +
		                '<div class="1y box"><div class="qs-ui-triangle-sm"><div class="sdservice l3"></div><div class="sdinfo l7"></div><div class="sdmfg l2"></div><div class="sdmkt l4"></div></div></div>' +
		                '<div class="3y box"><div class="qs-ui-triangle-sm"><div class="sdservice l1"></div><div class="sdinfo l6"></div><div class="sdmfg l2"></div><div class="sdmkt l4"></div></div></div>' +
		            '</div>' +
		            '<div class="subTitle">' +
		                '<div class="title">1Wk</div>' +
		                '<div class="title">1Mo</div>' +
		                '<div class="title">3Mo</div>' +
		                '<div class="title">1Yr</div>' +
		                '<div class="title">3Yr</div>' +
		            '</div>' +
		        '</div>' + 
		        '<div class="qs-marketsectors-grid">' + 
		            '<div class="title"><b>Morningstar Indexes</b></div>' + 
		            '<div class="range">Day Change %</div>' + 
		            '<div class="dtgrid"></div>' + 
		        '</div>';
		        this.dom = $(html);
		        this.dom.appendTo(panel);
		        this.bindEvent();
		        var dtContainer = panel.find('.qs-marketsectors-grid .dtgrid');
		        this.initDTGrid(dtContainer);
			},
			initDTGrid: function(container){
                this.dtgrid = new Util.DataGrid(container, {}, {
                    column: [{
                        header: "rowid",
                        dataIndex: 'rowid',
                        width: 0,
                        dataType: 'string',
                        hide: true
                    }, {
                        header: "Symbols",
                        dataIndex: 'Symbols',
                        width: '80%',
                        dataType: 'string'
                    }, {
                        header: "chg",
                        dataIndex: 'chg',
                        width: '20%',
                        align: 'right',
                        dataType: 'html'
                    }],
                    autoWidth: true,
                    height: 200,
                    htmlLayer: 'div',
                    headerRow: false,
                    rowDragable: true,
                    rowDropable: true,
                    rowDragDropGroup: 'GRID1'
                }, {});
            },
            bindEvent: function(){
                var self = this;
                this.dom.find('.qs-ui-triangle div, .qs-ui-triangle-sm div').hover(function(){
                    self.mouseenter(this);
                }, function(){
                    self.mouseleave(this);
                });
            },
            mouseenter: function(o){
				var type = o.className.split(' ')[0];
				var frequency = o.parentNode.parentNode.className.split(' ')[0];
				this.show(type, frequency);
			},
			show: function(type, frequency){
				this.dom.find('.range').html(this.frequencyRange[frequency]);
				var data = sector.dataManager.getGridData(type, frequency);
				this.dtgrid.reBindData(data);
			},
            mouseleave: function(o){},
            initColor: function(){
				var self = this;
				var boxs = this.dom.find('.box .qs-ui-triangle, .box .qs-ui-triangle-sm');
				boxs.each(function(){
					var frequency = this.parentNode.className.split(' ')[0];
					var chgs = sector.dataManager.getChg(frequency), d = [];
					for (var i = 0; i < chgs.length; d[i] = Math.abs(chgs[i]), chgs[i] = parseFloat(chgs[i], 10), i++);
					var b = Math.max.apply(Math, d);
					
					for (var i = 0, l = chgs.length; i < l; i++) {
						var v = chgs[i];
						var idx = 7 - Math.floor(7 * (v + b) / (2 * b));
						idx == 7 ? idx-- : null;
						
						loc = (i == l - 1 ? 0 : i + 1)
						var cls = this.childNodes[loc].className;
						cls = cls.replace(/l[\d]$/, 'l' + idx);
						this.childNodes[loc].className = cls
					}
				});
			}
		});
		
		this.delta.init();
	},
    initValuation: function(panel){
		this.valuation = {
			tabmenu: null,
			dom:null,
			miniChart:null,
			dtgrid: null
		};
		
		$.extend(this.valuation, {
			init:function(){
				//var html = '<div></div><div></div>';
		        this.dom = panel;
		       // this.dom.appendTo(panel);
				
				this.initTabMenu();
				this.dom.append('<div class="minichart" style="width: 250px; height:100px;"></div>');
				this.miniChart = new minichart(this.dom.find('.minichart')); 
				this.dom.find('.minichart canvas').css({width:268,height:100});
				//this.miniChart.changeOutSize(250,100)
				this.initDTGrid();
			},
			initTabMenu: function(container){
				container = container || this.dom;
				var self = this;
				this.tabmenu = new Util.TabMenu(container, [{
					txt: "Sensitive",
					val: "sensitive",
					closable: false
				}, {
					txt: "Cyclical",
                    val: "cyclical",
                    closable: false
				}, {
                    txt: "Defensive",
                    val: "defensive",
                    closable: false
                }], {
					onActive: function(tab){
						switch (tab.val) {
							case "sensitive":
								break;
							case "cyclical":
								break;
							case "defensive":
								break;
						}
					}
				}, {
					tabsList: false,
					closeAction: 'hide',
					autoSlideToActiveTab: false,
					activeTabId: "delta",
					rearrange: false
				});
			},
			initDTGrid:function(container){
				container = container || this.dom;
				this.dtgrid =  new Util.DataGrid(container, {}, {
                    column: [{
                        header: "rowid",
                        dataIndex: 'rowid',
                        width: 0,
                        dataType: 'string',
                        hide: true
                    }, {
                        header: "Symbols",
                        dataIndex: 'Symbols',
                        width: '80%',
                        dataType: 'string'
                    }, {
                        header: "Valuation",
                        dataIndex: 'valuation',
                        width: '20%',
                        align: 'right',
                        dataType: 'html'
                    }],
                    autoWidth: true,
                    height: 200,
                    htmlLayer: 'div',
                   //headerRow: false,
                    rowDragable: true,
                    rowDropable: true,
                    rowDragDropGroup: 'GRID1'
                }, {});
			}
		});
		
		this.valuation.init();
	},
	changeOutSize: function(w, h){
		w = w || this.container.width();
		h = h || this.container.height();
		this.tabmenu.setPanelOutSize(w, h - 26);
	}
};

//subtype 14_6
var QS_MarketCommodityFutures = function(){
	this.profile = {}
	this.HTML = '<div class="qs_marketcommodityfutures"></div>';	
	this.moduleHTML = '<div class="module">'+
	           '<div class="pic">Pic</div>'+
			   '<h5 class="sector row">sector</h5>'+
		      // '<div class="symbol row">symbol</div>'+
			   '<div class="LastPrice row">LastPrice</div>'+
			   '<div class="Chg row">Chg%</div>'+
			   '<div class="Chgper row" style="text-indent:60px;">Chg%</div>'+
			   '<div class="Date row">Date</div>'+
	       '</div>';
		   
	/**
	 * @GC  @GCJ1  Comex Gold       66:@GC1J   /66:@GC1J
	 * @CL  @CLK1  Sweet Crude Oil  67:@CL1K   /67:@CL1K
     * @NG  @NGK1  Natural Gas      67:@NG1K   /67:@NG1K
	 */   
	/** 
	 this.symbols = ['/66:@GC1J','/67:@CL1K','/67:@NG1K'];
	this.validSymbolsReady = false;
	this.validSymbols = [];
	this.symbolsNameMap ={
	   '66:@GC1J':"Comex Gold",'67:@CL1K':"Sweet Crude Oil",'67:@NG1K':"Natural Gas"
	}
	
	if (typeof QS_FuturesMap == 'undefined') {
	  	QS_FuturesMap = {};
	}
	  
	  
	this.dMap = {0:'Sunday', 1:"Monday", 2:"Tuesday", 3:"Wednesday", 4:"Thursday", 5:"Friday", 6:"Saturday"};
    this.mMap = {0:'January', 1:"February", 2:"March", 3:"April", 4:"May", 5:"June", 6:"July", 7:"August", 8:"September", 9:"October", 10:"November", 11:"December"};
	this.symbolsDomMap = {};
	this.tValidation = new tickerValidation(17);
}

QS_MarketCommodityFutures.prototype = {
	init: function(ContainerId, Profile, Sid){
		this.containerId = ContainerId;
		this.container = $('#' + ContainerId);
		this.id = Sid;
		this.profile = Profile;
		this.el = $(this.HTML);
		this.el.appendTo(this.container);
		
		this.scrollPanel = new Util.ScrollPanel(this.el);
		this.bindModules();
	},
	
	_checkTickers: function(){
		var self = this;
		this.tValidation.checkTickers(this.symbols, function(validSymbols){
			self.validSymbolsReady = true;
			self.validSymbols = validSymbols;
			//callback.call(self);
			self.bindModules()
		});
	},
	
	bindModules: function(){
		if (this.validSymbolsReady == false) {
			this._checkTickers();
//			this.validSymbols = ['66:@GC1J','67:@CL1K','67:@NG1K'];
//			this.validSymbolsReady = true;
//			this.bindModules();
		}
		else {
			for (var idx = 0, l = this.validSymbols.length; idx < l; idx++) {
				this.bindModule(this.validSymbols[idx]);
			}
			this.changeOutSize();
		}
	},
	
	bindModule: function(gKey, el){
		var el = $(this.moduleHTML);
		var imgObj = el.find('.pic');
		switch (gKey) {
			case '66:@GC1J':{
				imgObj.html('<img src="//rtqimg.morningstar.com/theme/'+QS_Theme+'/ico_gold.png" />');
			}break;
			case '67:@CL1K':{
			    imgObj.html('<img src="//rtqimg.morningstar.com/theme/'+QS_Theme+'/ico_crude.png" />');
			}break;
			case '67:@NG1K':{
                imgObj.html('<img src="//rtqimg.morningstar.com/theme/'+QS_Theme+'/ico_natgas.png" />');
            }break;
		}
		this._flashModule(gKey, el);
		if (!this.symbolsDomMap[gKey]) 
			this.symbolsDomMap[gKey] = el;
		el.appendTo(this.el);
	},
	
	_flashModule: function(gKey, el){
		el.find(".sector").html(this.symbolsNameMap[gKey]);
		this._flashField(gKey, 'Date', el);
		this._flashField(gKey, 'LastPrice', el);
		this._flashField(gKey, 'Chg', el);
		this._flashField(gKey, 'Chg%', el);
	},
	
	_flashField: function(gKey, field, el){
		var value = 0.00;
		if (typeof(gData[gKey]) != 'undefined' && typeof(gData[gKey][field]) != 'undefined') {
			value = gData[gKey][field];
		}
		if (field == 'Date') {
			var d = null;
			if (!/^\d{4}\-\d{1,2}\-\d{1,2}$/.test(value)) {
				d = new Date();
			}
			else {//YYYY-MM-DD
				var t = value.split("-");
				d = new Date(t[0], parseInt(t[1]) - 1, t[2]);
			}
			//value = this.dMap[d.getDay()] + ',' + this.mMap[d.getMonth()] + ' ' + d.getDate() + ', ' + d.getFullYear();
			value = this.mMap[d.getMonth()] + ' ' + d.getDate() + ', ' + d.getFullYear();
			el.find(".Date")[0]['innerHTML'] = value;
		}
		else {
			this._updateFieldDom(field, el.find("." + (field == "Chg%" ? "Chgper" : field))[0], value, value, true);
		}
	},
	
	_updateFieldDom: function(field, el, data, oldValue, needFlash){
		var _flashMethod = needFlash === false ? (function(){}) : flash;
		switch (field) {
			case 'LastPrice':
				_flashMethod(el, data, oldValue);
				data = formatDoubledata(data, "future");
				el['innerHTML'] = data;
				break;
			case 'Chg':
			case 'Chg%':
				if (needFlash !== false) {
					flashWithDirectional(el, data, oldValue, data >= 0);
				}
				else {
					el.style.color = data >= 0 ? QS_Style.greenFontColor : QS_Style.redFontColor;
				}
				data = formatDoubledata(data, "future");
				if(field=="Chg%")data=data+"%";
				el['innerHTML'] = data;
				break;
			default:
				break;
		}
	},
	
	updateData: function(gKey, aData, needFlash){
		if (this.symbolsDomMap[gKey]) {
            for (var field in aData) {
				var el = this.symbolsDomMap[gKey].find('.' + (field == "Chg%" ? "Chgper" : field))[0];
				var data = aData[field].value;
				var oldValue = aData[field].oValue;
				this._updateFieldDom(field, el, data, oldValue, needFlash);
			}
		}
	},
	
	changeOutSize: function(w, h){
        w = w || this.container.width();
        h = h || this.__winObj.contentEl.height();
		
		this.scrollPanel.reSize(w, h);
	}
}

*/
           